<?php


namespace app\crm\model;


use app\admin\model\Common;


use think\facade\Db;
use app\admin\model\ShopModel;






class OrderStatistics extends Common


{





    protected $name = 'shop_order';


    /**


     * 优惠明细列表


     * @param  array $request 请求参数


     * @return array


     * @author Mr.Liu


     * @create 2021-11-27 17:25


     */


    public function getDataList(array $request): array


    {


        try {


            $shopIds= $request['shopIds'] ?? '';


            $request = $this->fmtRequest($request);


            $map     = $request['map'] ?? [];


            $where   = [];


            array_push($where, ['g.is_gift', '=', 1]);


            array_push($where, ['s.type', '<>', 2]);//只显示直营店数据



            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id


            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;


            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;


            // 获取客户数据权限 的客户名称


            if ($shopIds)


            {


                array_push($where, ['o.shop_id', 'in', $shopIds]);


            }


            if ($shop_id)


            {


                //门店名称搜索


                array_push($where, ['o.shop_id', '=', $shop_id]);


            }


            // 时间


            if($start_time && $end_time)


            {


                array_push($where, ['o.create_time', 'between', "$start_time,$end_time"]);


            }


            array_push($where, ['o.status', '=', 2]);


            $sqlQuery = Db::name('shop_order_goods')->alias('g')


                ->join('shop_order o', 'g.order_id = o.id', 'LEFT')


                ->join('customer c', 'o.uid = c.id', 'LEFT')


                ->join('shop s', 'o.shop_id = s.shop_id', 'LEFT')//判断直营店


                ->where($where)->whereOr('g.kingdee_code','101.12.098');





            $dataCount = $sqlQuery->count();


            if ($dataCount) {


                $field = 'o.consignee, g.pay_price, g.goods_price, g.number,g.goods_id,g.goods_name,c.telephone,g.is_gift,o.shop_name';


                $list = $sqlQuery->field($field)


                    ->when(!(isset($request['no_page']) && $request['no_page']), function ($query) use ($request) {


                        $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);


                    })


                    ->order('o.uid desc')


                    ->select()->toArray();


            }


            $sum=0;


            foreach ($list as $key=>$value)


            {


                if ($value['is_gift'])


                {


                    $sum_price=bcmul($value['goods_price'],$value['number'],2);


                    $sum+=abs($sum_price);


                    $list[$key]['price']=abs($sum_price);


                }else


                {


                    $sum_price=bcmul($value['pay_price'],$value['number'],2);


                    $sum+=abs($sum_price);


                    $list[$key]['price']=abs($sum_price);


                }


            }





            $data              = [];


            $data['total_price']=$sum ?? 0;


            $data['list']      = $list ?? [];


            $data['dataCount'] = $dataCount ?? 0;


            return $data;


        } catch (\Exception $e) {


        }





        $this->error = '暂无此数据';


        return [];


    }








    /**


     * 财务报表（销售日报表）


     * @param  array $request 请求参数


     * @return array


     * @author Mr.Liu


     * @create 2021-11-27 17:25


     */


    public function getDayList(array $request): array


    {


        try {


            $shopIds= $request['shopIds'] ?? '';


            $request = $this->fmtRequest($request);


            $map     = $request['map'] ?? [];


            $where   = [];


            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id


            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : strtotime(date('Y-m-d',time()));


            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : strtotime(date('Y-m-d',time()). ' 23:59:59');


            array_push($where, ['s.type', '<>', 2]);//只显示直营店数据


            // 获取客户数据权限 的客户名称


            if ($shopIds)


            {


                array_push($where, ['o.shop_id', 'in', $shopIds]);


            }


            if ($shop_id)


            {


                //门店名称搜索


                array_push($where, ['o.shop_id', '=', $shop_id]);


            }


            // 时间


            if($start_time && $end_time)


            {


                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);


            }


            array_push($where, ['o.status', '=', 2]);


            $sqlQuery = Db::name('shop_order_goods')->alias('g')


                ->join('shop_order o', 'g.order_id = o.id', 'LEFT')


                ->join('customer c', 'o.uid = c.id', 'LEFT')


                ->join('shop s', 'o.shop_id = s.shop_id', 'LEFT')//判断直营店


                ->where($where);


            $dataCount = $sqlQuery->count();

            if ($dataCount) {


                $field = 'o.consignee, g.pay_price,g.goods_id,g.goods_name,g.kingdee_code,g.number,c.telephone,g.is_gift,o.shop_name';


                $list = $sqlQuery->field($field)


                    ->when(!(isset($map['no_page']) && $map['no_page']), function ($query) use ($request) {


                        $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);


                    })


                    ->order('o.uid desc')


                    ->select()->toArray();


                $total=0;


                $discount=0;


                foreach ($list as $key=>$value)


                {


                    $sum_price=$list[$key]['sum_price']=bcmul($value['pay_price'],$value['number'],2);
                    if($value['goods_id'] == 170)
                    {

                    }


                    if ($value['kingdee_code']=='101.12.098')


                    {


                        $discount+=abs($sum_price);


                    }else


                    {


                        $total+=abs($sum_price);


                    }


                }


            }

            $where = [];
            array_push($where,['b.deal_time','>=',$start_time]);
            array_push($where,['b.deal_time','<=',$end_time]);
            array_push($where,['b.status','=',2]);

            array_push($where,['a.goods_id','=',170]);
            $manjian = Db::name('shop_order_goods')->alias('a')
                ->join('shop_order b','b.id = a.order_id','left')
                ->where($where)
                ->sum('a.number*a.pay_price');
            $where = [];
            array_push($where,['b.deal_time','>=',$start_time]);
            array_push($where,['b.deal_time','<=',$end_time]);
            array_push($where,['b.status','=',2]);
            array_push($where,['a.is_gift','=',1]);
            $gift = Db::name('shop_order_goods')->alias('a')
                ->join('shop_order b','b.id = a.order_id','left')
                ->where($where)
                ->sum('a.number*a.goods_price');
            $where = [];
            array_push($where,['deal_time','>=',$start_time]);
            array_push($where,['deal_time','<=',$end_time]);
            array_push($where,['status','=',2]);
            $xiaoshou = DB::name('shop_order')
                ->where($where)
                ->sum('total_amount');
            $where = [];
            array_push($where,['deal_time','>=',$start_time]);
            array_push($where,['deal_time','<=',$end_time]);
            array_push($where,['status','=',2]);
            array_push($where,['type','=',2]);

            $tuihuo = DB::name('shop_refund_order')
                    ->where($where)
                    ->sum('total_amount');
            $data              = [];
//            $data['total_price']=bcadd($total,0,2) ?? 0;
            $data['total_price']=bcsub($xiaoshou,$tuihuo,2) ?? 0;




//            $data['discount_price']=bcadd($discount,0,2) ?? 0;
            $data['discount_price']=bcsub($manjian,$gift,2) ?? 0;



            $data['receivable_price']=bcadd($data['total_price'],$data['discount_price'],2) ?? 0;


            $data['list']      = $list ?? [];


            $data['dataCount'] = $dataCount ?? 0;


            return $data;


        } catch (\Exception $e) {

            return ['msg'=>$e->getMessage()];
        }





        $this->error = '暂无此数据';


        return [];


    }








    /**


     * 进店成交明细表


     * @param  array $request 请求参数


     * @return array


     * @author Mr.Liu


     * @create 2021-11-27 17:25


     */


    public function getOrderList($request)
    {


        try {


        $shopIds= $request['shopIds'] ?? '';

        $type = $request['type'];


        $request = $this->fmtRequest($request);

        $map     = $request['map'] ?? [];


        $where   = [];


        $data              = [];



        if ($map['start_time']!=''&& $map['end_time']!='')

        {
			$s = $map['start_time'];
			$e = $map['end_time'];


			$start_time = strtotime($s);
			$end_time   = strtotime($e) + 86399;


			//var_dump(strtotime("-1 month",$timet));
			$data['time_achievement']              = '100%';//时间达成率

			$last_start_time=strtotime(date("Y-m-01",strtotime("-1 month",$start_time)));//业务统计开始时间
			//var_dump($last_start_time);
			$old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$start_time)));//进店 成交开始时间
			$old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//进店 成交结束时间


        }else{


            $days=date('t', time());


            $today=date('d', time());


            $data['time_achievement']              =$days>0 ? (bcdiv($today,$days,2)*100).'%' : 0;//时间达成率


            $start_time=strtotime( date('Y-m-1'));


            $end_time=time();


            $last_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-1 month",$start_time)));


            $old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$start_time)));//进店 成交开始时间


            $old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//进店 成交结束时间


        }

            // 获取客户数据权限 的客户名称
            if ($shopIds) {
                array_push($where, ['s.shop_id', 'in', $shopIds]);
            }
        //array_push($where, ['c.create_time', 'between', "$start_time,$end_time"]);

			//$closeShopId = [74076159037951,];
            //array_push($where, ['s.type', '=', 1]);//只有直营店数据
			array_push($where, ['s.status', '=', 1]);//只有直营店数据

			array_push($where, ['s.shop_id', '<>', 74076159037951]);//只有直营店数据
			//array_push($where, ['s.shop_id', '<>', 73782774859952]);//只有直营店数据

            if(!empty($type))
            {
                array_push($where,['type','=',$type]);

            }
        $sqlQuery = Db::name('shop')->alias('s')
            ->join('shop_market m', 's.market_id = m.id', 'LEFT')
            ->where($where);

        $dataCount = $sqlQuery->count();

        $arr=[];

        if ($dataCount) {
            $field = 's.shop_id, s.shop_name,m.name,s.shop_type,s.market_id';

            $list = $sqlQuery->field($field)
                ->order('m.id desc')
                ->select()->toArray();

            $arr=array_column($list,null,'shop_id');

            $shop_id=array_column($list,'shop_id');

            //护理量查询
			// $userList = Db::name('shop_person')->alias('s')
   //                      ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
   //                      ->where([['s.shop_id', 'in', $shop_id],['s.status','<>',3],['sp.type', '=', 1]])
   //                      ->column('s.id');

// 			$userList = Db::name('shop_person')->alias('s')
// 				                     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
// 				                      ->where([['s.shop_id', 'in', $shop_id],['s.status','=',1],['s.name','<>','虚拟员工核销专用']])
// 				                     ->column('s.id');
//             // 计算1
//             $service1=Db::name('service_log')->where([['nurse_id_one', 'in', $userList], ['nurse_id_two','=','0'], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
//             //->field('count(id) as sum,shop_id')->group('shop_id')

//             $service1=array_column($service1,null,'shop_id');

//             // 计算0.5
//             $service2=Db::name('service_log')->where([['nurse_id_one', 'in', $userList], ['nurse_id_two','in',$userList], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();

//             $service2=array_column($service2,null,'shop_id');

//             // 计算1
//             $service3=Db::name('service_log')->where([['nurse_id_one', '=', '0'], ['nurse_id_two','in',$userList], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
//             $service3=array_column($service3,null,'shop_id');
            
            
            
            // 查询所有门店的有效员工（按 shop_id 分组）
            $shopEmployees = Db::name('shop_person')
                ->where([
                    ['status', '=', 1],
                    ['name', '<>', '虚拟员工核销专用']
                ])
                ->field('shop_id, GROUP_CONCAT(id) as employee_ids')  // 按 shop_id 分组，合并员工ID
                ->group('shop_id')
                ->select()
                ->toArray();
            
            // 转换为结构：shop_id => [员工ID数组]
            $employeeMap = [];
            foreach ($shopEmployees as $item)
            {
                $employeeMap[$item['shop_id']] = explode(',', $item['employee_ids']);
            }
            // var_dump($employeeMap);die;
            $service1 = $service2 = $service3 = [];
            foreach($employeeMap as $shopId => $userList)
            {
                $service1[$shopId] = Db::name('service_log')
                ->where([['nurse_id_one', 'in', $userList], ['nurse_id_two','=','0'], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])
                ->where('shop_id',$shopId)
                ->field('count(id) as sum,shop_id')->group('shop_id')
                ->find();
                $service2[$shopId] = Db::name('service_log')
                ->where([['nurse_id_one', 'in', $userList], ['nurse_id_two','in',$userList], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])
                ->where('shop_id',$shopId)
                ->field('count(id) as sum,shop_id')
                ->group('shop_id')
                ->find();
                $service3[$shopId] = Db::name('service_log')
                ->where([['nurse_id_one', '=', '0'], ['nurse_id_two','in',$userList], ['create_time', 'between', "$start_time,$end_time"],['category_id','in',[1,8,10,11,4,12]]])
                ->where('shop_id',$shopId)
                ->field('count(id) as sum,shop_id')
                ->group('shop_id')
                ->find();
            }
            
            

            /* 新增护理手工 */
//            $service_log_control = Db::name('service_log_control')->where([['create_time', 'between', "$start_time,$end_time"]])->field('count(service_item) as sum,shop_id')->group('shop_id')->select()->toArray();
//            $service_log_control = array_column($service_log_control,null,'shop_id');

            $serviceCraft = Db::name('service_log')->where([['create_time', 'between', "$start_time,$end_time"]])->field('nurse_one_project,nurse_two_project,shop_id')->select()->toArray();
            $list_five = [];
            if(!empty($serviceCraft)){
                foreach($serviceCraft as $kk=>$vv){
                    if(isset($list_five[$vv['shop_id']])){
                        $list_five[$vv['shop_id']][]= !empty($vv['nurse_one_project'])?count(explode(',',$vv['nurse_one_project'])):0;
                        $list_five[$vv['shop_id']][]= !empty($vv['nurse_two_project'])?count(explode(',',$vv['nurse_two_project'])):0;
                    }else{
                        $list_five[$vv['shop_id']][] = !empty($vv['nurse_one_project'])?count(explode(',',$vv['nurse_one_project'])):0;
                        $list_five[$vv['shop_id']][] = !empty($vv['nurse_two_project'])?count(explode(',',$vv['nurse_two_project'])):0;
                    }
                }
            }



            /* 店长核销数量 */
			$serviceShop=Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['create_time', 'between', "$start_time,$end_time"], ['station_name', '<>', '']])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
			$serviceShop=array_column($serviceShop,null,'shop_id');

            //网络进店
            //$internet=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['first_time|second_time', 'between', "$start_time,$end_time"], ['source_id', 'not in', [46,47,48,49,583]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
			$internet=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['first_time|second_time', 'between', "$start_time,$end_time"], ['source_id', 'in', [43,44,50,51,52,54,55,56,118,584,609,597,654]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();

            $internet=array_column($internet,null,'shop_id');

            //转介绍
            $transfer_introduction=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['first_time|second_time', 'between', "$start_time,$end_time"], ['source_id' ,'=', '49']])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
            $transfer_introduction=array_column($transfer_introduction,null,'shop_id');

            //外联  店转不计算门店进店统计
            $outreach=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['first_time|second_time', 'between', "$start_time,$end_time"], ['source_id', 'in', [46,47,48,583,608]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
            $outreach=array_column($outreach,null,'shop_id');

            //线上导客数量
            $internet_total=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['create_time', 'between', "$start_time,$end_time"], ['source_id', 'not in', [46,47,48,49,583,608,665]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
            $internet_total=array_column($internet_total,null,'shop_id');

            //其他渠道
            $qita=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['create_time', 'between', "$start_time,$end_time"], ['source_id', '=', 665]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();
            $qita=array_column($qita,null,'shop_id');

            //体验个数

			//体验项目-- 体验-疤痕 -168 |体验--身体项目  -165 |体验--面部护理 -150 |体验--痘痘 -150
			$experience_good = [150,168,165,686];
			//查询销售出库单中的是否体验个数---2022.04.11 修改
            //$experience_total=Db::name('shop_order')->where([['shop_id', 'in', $shop_id], ['deal_time', 'between', "$start_time,$end_time"],['order_experience', '=', 1],['status', '=', 2]])->field('count(DISTINCT(uid)) as sum,shop_id')->group('shop_id')->select()->toArray();

			$experience_total=Db::name('service_log')->where([['shop_id', 'in', $shop_id],['create_time', 'between', "$start_time,$end_time"], ['goods_id', 'in', $experience_good]])->field('count(DISTINCT(customer_id)) as sum,shop_id')->group('shop_id')->select()->toArray();
            $experience_total=array_column($experience_total,null,'shop_id');

            //体验成交个数 收款单中 1是体验单，2是成交的金额需要大于500以上的新单人数统计,3不算收款调整
            $experience_deal=Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['deal_time', 'between', "$start_time,$end_time"],['is_experience', '=', 1],['status', '=', 2],['type', '=', 3],['order_type', '=', 1],['pay_amount', '>', 500],['refund_type', '<>', '101.03']])->field('count(DISTINCT(uid)) as sum,shop_id')->group('shop_id')->select()->toArray();
            $experience_deal=array_column($experience_deal,null,'shop_id');

           //成交个数 计算收款单新单个数（新单是500元以上的新单）,不算收款调整
            /* $receive_deal=Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['deal_time', 'between', "$start_time,$end_time"],['status', '=', 2],['type', '=', 3],['order_type', '=', 1],['pay_amount', '>', 500],['refund_type', '<>', '101.03']])->field('count(DISTINCT(uid)) as sum,shop_id')->group('shop_id')->select()->toArray();

            $receive_deal=array_column($receive_deal,null,'shop_id'); */

			//查询当前时间段的 成交个数
			$receive_deal=Db::name('customer')->where([['shop_id', 'in', $shop_id], ['cj_time', 'between', "$start_time,$end_time"],['cj_money', '>=', 500]])->field('count(DISTINCT(id)) as sum,shop_id')->group('shop_id')->select()->toArray();

			$receive_deal=array_column($receive_deal,null,'shop_id');

            $nine_start_time = 1725120000; //24年9月1日 0：00：00

            $shop_types = array_unique(array_column($arr,'shop_type'));

            $shopModel = new ShopModel();

            $newsXDMoneyAll =  $budanMoneyAll = $newsXDMoneyAllOne = $newsXDMoneyAllTwo = $budanMoneyAllOne = $budanMoneyAllTwo =   [];

            if( $start_time >= $nine_start_time && $end_time > $nine_start_time ){
                if(in_array(1,$shop_types)){
                    $mzXDMoneyAllOne = $shopModel->outpatientPerform($shopIds,1,$start_time,$end_time); //门诊新单业绩
                    $mzBDMoneyAllTwo = $shopModel->outpatientPerform($shopIds,2,$start_time,$end_time); //门诊补单业绩
                }
                if(in_array(2,$shop_types)){
                    $shopXDMoneyAllOne = $shopModel->shopPerform($shopIds,1,$start_time,$end_time);  //门店新单业绩
                    $shopBDMoneyAllTwo = $shopModel->shopPerform($shopIds,2,$start_time,$end_time);  //门店补单业绩
                }
            }else {
                if ($start_time < $nine_start_time && $end_time > $nine_start_time) {
                    if (in_array(1, $shop_types)) {
                        $mzXDMoneyAllOne = $shopModel->outpatientPerform($shopIds, 1, $nine_start_time, $end_time); //门诊新单业绩
                        $mzBDMoneyAllTwo = $shopModel->outpatientPerform($shopIds, 2, $nine_start_time, $end_time); //门诊补单业绩
                    }
                    if (in_array(2, $shop_types)) {
                        //门店
                        $shopXDMoneyAllOne = $shopModel->shopPerform($shopIds, 1, $nine_start_time, $end_time);  //门店新单业绩
                        $shopBDMoneyAllTwo = $shopModel->shopPerform($shopIds, 2, $nine_start_time, $end_time);  //门店补单业绩
                    }
                    $end_time = 1725119999; //24年8月31日 23 59 59
                }

                $newsXDMoneyAll =$this->sumShopPayMoneyNewMZAll('XD',$shopIds,$start_time,$end_time);

                $budanMoneyAll =$this->sumShopPayMoneyNewMZAll('BD',$shopIds,$start_time,$end_time);

                $newsXDMoneyAllOne =$this->sumShopPayMoneyNewAll('XD',$shopIds,1,$start_time,$end_time);

                $newsXDMoneyAllTwo =$this->sumShopPayMoneyNewAll('XD',$shopIds,2,$start_time,$end_time);

                $budanMoneyAllOne =$this->sumShopPayMoneyNewAll('BD',$shopIds,1,$start_time,$end_time);

                $budanMoneyAllTwo =$this->sumShopPayMoneyNewAll('BD',$shopIds,2,$start_time,$end_time);

            }


            foreach ($arr as $key=>$value) {

				 if(in_array($value['market_id'],[8,9,10,11]))
				 {
                     $newsXDMoney_old = !isset($newsXDMoneyAll[$value['shop_id']])?0:$newsXDMoneyAll[$value['shop_id']];
                     $budanMoney_old = !isset($budanMoneyAll[$value['shop_id']])?0:$budanMoneyAll[$value['shop_id']];
				 }else{
                     if($value['shop_type'] == 1)
                     {
                         $newsXDMoney_old = !isset($newsXDMoneyAllOne[$value['shop_id']])?0:$newsXDMoneyAllOne[$value['shop_id']];
                         $budanMoney_old = !isset($budanMoneyAllOne[$value['shop_id']])?0:$budanMoneyAllOne[$value['shop_id']];
                     }else{
                         $newsXDMoney_old = !isset($newsXDMoneyAllTwo[$value['shop_id']])?0:$newsXDMoneyAllTwo[$value['shop_id']];
                         $budanMoney_old = !isset($budanMoneyAllTwo[$value['shop_id']])?0:$budanMoneyAllTwo[$value['shop_id']];
                     }
				 }

				if($value['shop_type'] == 1){
					//门诊
					$newsXDMoney = empty($mzXDMoneyAllOne[$value['shop_id']])?0:$mzXDMoneyAllOne[$value['shop_id']];
					$budanMoney = empty($mzBDMoneyAllTwo[$value['shop_id']])?0:$mzBDMoneyAllTwo[$value['shop_id']];
				}else{
					//门店
					$newsXDMoney = empty($shopXDMoneyAllOne[$value['shop_id']])?0:$shopXDMoneyAllOne[$value['shop_id']];
					$budanMoney = empty($shopBDMoneyAllTwo[$value['shop_id']])?0:$shopBDMoneyAllTwo[$value['shop_id']];
				}

                $newsXDMoney = bcadd($newsXDMoney,$newsXDMoney_old,2);
                $budanMoney = bcadd($budanMoney,$budanMoney_old,2);

                $service_sum1 = $service1[$key]['sum'] ?? 0;

                $service_sum2 = $service2[$key]['sum'] ?? 0;

                $service_sum3 = $service3[$key]['sum'] ?? 0;


                $control_num = $service_log_control[$key]??0;
                $serviceCraft_num = isset($list_five[$key])?array_sum($list_five[$key]):0;


                $controlnum = bcadd($control_num,$serviceCraft_num);




                $service_sum = $service_sum1+$service_sum2+$service_sum3;

				//echo '数据排查 --666';echo '<br/>';

                $arr[$key]['sevice'] = isset($service1[$key]) ? $service_sum : 0;//护理量

                $arr[$key]['controlnum'] = $controlnum;//护理手工

				$arr[$key]['sevice_shop'] = isset($serviceShop[$key]) ? $serviceShop[$key]['sum'] : 0;//店长核销数量


                $internet_num = $arr[$key]['internet'] = isset($internet[$key]) ? $internet[$key]['sum'] : 0;//进店数量


                $introduction_num = $arr[$key]['transfer_introduction'] = isset($transfer_introduction[$key]) ? $transfer_introduction[$key]['sum'] : 0;//转介绍数量


                $outreach_num = $arr[$key]['outreach'] = isset($outreach[$key]) ? $outreach[$key]['sum'] : 0;//门店外联数量

				$qita_num = $arr[$key]['qita'] = isset($qita[$key]) ? $qita[$key]['sum'] : 0;//其他渠道数量


                $arr[$key]['enter_total_num'] = bcadd(bcadd($internet_num, bcadd($outreach_num, $introduction_num, 0), 0),$qita_num,0);//进店数量合计


				//店长端核销数量 占比
				if ($arr[$key]['sevice_shop'])


				{


				    $arr[$key]['sevice_shop_rate'] =$arr[$key]['sevice'] >0 ? (bcdiv($arr[$key]['sevice_shop'],$arr[$key]['sevice'],4)*100).'%' : 0;//店长核销占比


				}else


				{


				    $arr[$key]['sevice_shop_rate']= '0%';//店长核销占比


				}




                $internet_totals=$arr[$key]['internet_total'] = isset($internet_total[$key]) ? $internet_total[$key]['sum'] : 0;//线上导客数量


                if ($internet_totals)


                {


                    $arr[$key]['internet_entry_rate']=$internet_totals> 0 ?(bcdiv($internet_num,$internet_totals,4)*100).'%' : 0;//线上进店率


                }else


                {


                    $arr[$key]['internet_entry_rate']= '0%';//线上进店率


                }


                $arr[$key]['experience_total'] = isset($experience_total[$key]) ? $experience_total[$key]['sum'] : 0;//体验个数


                $arr[$key]['experience_deal'] = isset($experience_deal[$key]) ? $experience_deal[$key]['sum'] : 0;//体验成交个数


                if ($arr[$key]['experience_total'])


                {


                    $arr[$key]['experience_rate'] =$arr[$key]['experience_total']>0? (bcdiv($arr[$key]['experience_deal'],$arr[$key]['experience_total'],4)*100).'%':0;//体验成交率


                }else


                {


                    $arr[$key]['experience_rate'] = '0%';//体验成交率


                }

				//echo '数据排查 --121212';echo '<br/>';
                $arr[$key]['receive_deal'] = isset($receive_deal[$key]) ? $receive_deal[$key]['sum'] : 0;//成交个数


                $receive_new_money1=isset($receive_new1[$key]) ? $receive_new1[$key]['sum'] : 0; //新单首门店是本门店收款单金额


                $receive_new_money2=isset($receive_new2[$key]) ? $receive_new2[$key]['sum'] : 0; //新单第二门店是本门店收款单金额


                $receive_new_money=bcadd($receive_new_money1,$receive_new_money2,2);//新单收款单总金额


                $refund_new_money1=isset($refund_new1[$key]) ? $refund_new1[$key]['sum'] : 0; //新单首门店是本门店退款单金额


                $refund_new_money2=isset($refund_new2[$key]) ? $refund_new2[$key]['sum'] : 0; //新单第二门店是本门店退款单金额


                $refund_new_money=bcadd($refund_new_money1,$refund_new_money2,2); //新单退款单总金额


                $receive_old_money1=isset($receive_old1[$key]) ? $receive_old1[$key]['sum'] : 0; //补单首门店是本门店收款单金额


                $receive_old_money2=isset($receive_old2[$key]) ? $receive_old2[$key]['sum'] : 0; //补单第二门店是本门店收款单金额


                $receive_old_money=bcadd($receive_old_money1,$receive_old_money2,2);//补单收款单总金额


                $refund_old_money1=isset($refund_old1[$key]) ? $refund_old1[$key]['sum'] : 0; //补单首门店是本门店收款单金额


                $refund_old_money2=isset($refund_old2[$key]) ? $refund_old2[$key]['sum'] : 0; //补单第二门店是本门店收款单金额


                $refund_old_money=bcadd($refund_old_money1,$refund_old_money2,2); //补单收款单总金额

				//$newsXDMoney  budanMoney
                //$arr[$key]['new_total'] = bcsub($receive_new_money,$refund_new_money,2);//新单金额
				$arr[$key]['new_total'] = $newsXDMoney;//新单金额

                //$arr[$key]['repair_total'] = bcsub($receive_old_money,$refund_old_money,2);//补单金额
				$arr[$key]['repair_total'] = $budanMoney;//补单金额

                $arr[$key]['job_total'] = bcadd($arr[$key]['new_total'],$arr[$key]['repair_total'],2);//业绩合计


               if ($arr[$key]['receive_deal'])


               {


                   $arr[$key]['sheet_money'] =$arr[$key]['receive_deal']>0 ? bcdiv($arr[$key]['new_total'],$arr[$key]['receive_deal'],2) :0;//均单值


               }else


               {


                   $arr[$key]['sheet_money'] =  '0.00';//均单值


               }


               if ($arr[$key]['enter_total_num'])


               {


                   $arr[$key]['turnover_rate'] =$arr[$key]['enter_total_num']>0? (bcdiv($arr[$key]['receive_deal'],$arr[$key]['enter_total_num'],4)*100).'%':0;//成交率


               }else


               {


                   $arr[$key]['turnover_rate'] =  '0%';//成交率


               }




            }


            $arr=array_values($arr);

			// echo '<pre>';
			// print_r($arr);
        }

        $service_list = array_column($arr,'sevice'); // 护理量
        $service_control = array_column($arr,'controlnum'); // 护理手工
		$serviceshop_list = array_column($arr,'sevice_shop'); // 店长核销数量
        $internet_list = array_column($arr,'internet'); // 网络进店
        $transfer_introduction_list = array_column($arr,'transfer_introduction'); // 转介绍
        $outreach_list = array_column($arr,'outreach'); // 门头外联
		$qita_list = array_column($arr,'qita'); // 其他
        $enter_total_num_list = array_column($arr,'enter_total_num'); // 合计
        $internet_total_list = array_column($arr,'internet_total'); // 线上导客
        $experience_total_list = array_column($arr,'experience_total'); // 体验个数
        $experience_deal_list = array_column($arr,'experience_deal'); // 体验成交个数

        $receive_deal_list = array_column($arr,'receive_deal'); // 成交个数

        $new_total_list = array_column($arr,'new_total'); // 新单金额

        $repair_total_list = array_column($arr,'repair_total'); // 补单金额
        $job_total_list = array_column($arr,'job_total'); // 业绩合计


        $heji = [
            'name' => '合计：',
            'sevice' => bcadd(array_sum($service_list),0,0),
            'controlnum' => bcadd(array_sum($service_control),0,0),
			'sevice_shop' => bcadd(array_sum($serviceshop_list),0,0),
            'internet' => bcadd(array_sum($internet_list),0,0),
            'transfer_introduction' => bcadd(array_sum($transfer_introduction_list),0,0),
            'outreach' => bcadd(array_sum($outreach_list),0,0),
			'qita' => bcadd(array_sum($qita_list),0,0),
            'enter_total_num' => bcadd(array_sum($enter_total_num_list),0,0),
            'internet_total' => bcadd(array_sum($internet_total_list),0,0),
            'experience_total' => bcadd(array_sum($experience_total_list),0,0),
            'experience_deal' => bcadd(array_sum($experience_deal_list),0,0),
            'receive_deal' => bcadd(array_sum($receive_deal_list),0,0),
            'new_total' => bcadd(array_sum($new_total_list),0,2),
            'repair_total' => bcadd(array_sum($repair_total_list),0,2),
            'job_total' => bcadd(array_sum($job_total_list),0,2),


            'internet_entry_rate' => array_sum($internet_total_list)>0 ? (bcdiv(array_sum($internet_list),array_sum($internet_total_list),4)*100).'%' : '0.00%',
            'experience_rate' => array_sum($experience_total_list)>0 ? (bcdiv(array_sum($experience_deal_list),array_sum($experience_total_list),4)*100).'%' : '0.00%',
            'turnover_rate' => array_sum($enter_total_num_list)>0 ? (bcdiv(array_sum($receive_deal_list),array_sum($enter_total_num_list),4)*100).'%' : '0.00%',

			'sevice_shop_rate' => array_sum($service_list)>0 ? (bcdiv(array_sum($serviceshop_list),array_sum($service_list),4)*100).'%' : '0.00%',

            'sheet_money' => array_sum($receive_deal_list)>0 ? round((bcdiv(array_sum($new_total_list),array_sum($receive_deal_list),4)),2) : '0.00',

            'enter_store_retain_rate' => '-',
            'deal_retain_rate' => '-',
        ];

        // echo "<pre>";
        // print_r($heji);
        // echo "</pre>";
        // exit;
        array_push($arr,$heji);
		$data3= [];
		foreach ($arr as $value)
		{
			if(empty($data3[$value['name']]))
			{
				$data3[$value['name']]['name']=$value['name'];
				$data3[$value['name']]['list']=[];
			}
			array_push($data3[$value['name']]['list'],$value);
		}

		$data              = [];

		$data['list'] = [];
		foreach ($data3 as $value) {
			array_push($data['list'], $value);
		}

		if(!empty($request['map']['export']))
		{
			$data['list'] = $arr ?? [];
		}


		$data['dataCount'] = $dataCount ?? 0;


		return $data;


	} catch (\Exception $e) {
		echo $e->getMessage();die;

	}
			// $this->error = '暂无此数据';


			// 	return [];
    }





	/*
	 * @ 新单金额和补单金额的 计算 逻辑----川渝市场的 新单/补单业绩计算
	 *
	 * @ 门店新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
	 *                       【加上】  门诊转到门店的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
	 *
	 * @ 门珍新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
	 *                       【加上】  非疗程不含店转的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
	 */
	public function sumShopPayMoneyNew($scene,$shopId,$shop_type,$startTime,$endTime,$person_id = 0){

        $map = $maps = [];
        if($person_id>0){
            array_push($maps,['r.sale_id','=',$person_id]);
            array_push($map,['sale_id','=',$person_id]);
        }
		switch ($scene) {
			case 'XD':

		        $where['order_type']=1;
				$wheret['r.order_type']=1;
				break;

		    case 'BD':

		        $where['order_type']=2;
				$wheret['r.order_type']=2;
				break;

		    default:

		        break;

		}
		//收款单中的疤痕业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount')
	        ->where('r.shop_id','=',$shopId)
            ->where($maps)
	        ->where($wheret)

	        ->where('g.refund_mode','<>','06')

	        ->where('r.type','=',3)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

	        ->find();

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//退款单中的疤痕业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			->field('sum(g.pay_price) as pay_amount')
	        ->where('r.shop_id','=',$shopId)
            ->where($maps)
	        ->where($wheret)

	        ->where('g.refund_mode','<>','06')

	        ->where('r.type','=',1)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

	        ->find();

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount,id')
            ->where($map)
			->where($where)

		    ->where('referral_shop_id','=',$shopId)

		    ->where('type','=',3)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->find();


		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        ->field('sum(g.pay_price * r.coefficient) as pay_amount')
            ->where($maps)
	        ->where($wheret)

	        ->where('r.shop_id','=',$shopId)

	        ->where('g.refund_mode','=','06')

	        ->where('r.type','=',1)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','<>','101.03')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })

	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

	        ->find();

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        ->field('sum(g.pay_price * r.coefficient) as pay_amount')

	        ->where('r.shop_id','=',$shopId)
            ->where($maps)
	        ->where($wheret)

	        ->where('g.refund_mode','=','06')

	        ->where('r.type','=',3)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

	        ->find();

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')

		    ->field('sum(pay_amount * coefficient) as pay_amount')

            ->where($map)

			->where($where)

		    ->where('shop_id','=',$shopId)

			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })->find();

		if($shop_type==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
			return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
		}
	}



	/*
	 * @ 疤痕业绩和项目业绩的 计算 逻辑----川渝市场的 疤痕和项目业绩计算
	 *
	 * @ 门店疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  门诊转到门店的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 *
	 * @ 门珍疤痕/项目业绩计算 ：收款单（不含店转）的疤痕/项目 实收金额 【减去】 退款单（不含店转）的疤痕/项目 实收金额
	 *                       【加上】  非疗程不含店转的 疤痕/项目 实收金额 【减去】 退款单是店转的 疤痕/项目金额 【加上】 收款单是店转的疤痕/项目金额；
	 */
	public function sumShopPayMoneyNewMZ($scene,$shopId,$shop_type,$startTime,$endTime,$person_id = 0){

        $maps = [];
        if($person_id>0){
            array_push($maps,['r.sale_id','=',$person_id]);

        }
		switch ($scene) {
			case 'XD':

		        $where['r.order_type']=1;
				break;

		    case 'BD':

		        $where['r.order_type']=2;
				break;

		    default:

		        break;

		}


		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
		    ->where($where)
            ->where($maps)
		    ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    ->column('r.pay_amount as pay_amount','r.id');
			//->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')

		    ->where('r.shop_id','=',$shopId)

            ->where($maps)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    //->column('r.pay_amount * r.coefficient as pay_amount','r.id');
			->column('r.pay_amount  as pay_amount','r.id');

		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

		$receive_sum = array_sum($receive);

		$refund_sum = array_sum($refund);

		return bcsub($receive_sum,$refund_sum,2);
	}






    /**


     * 进店保有率明细


     * @param  array $request 请求参数


     * @return array


     * @author Mr.Liu


     * @create 2021-11-27 17:25


     */


    public function getEnterOrderDetail(array $request): array


    {


        try {


            $request = $this->fmtRequest($request);


            $map     = $request['map'] ?? [];


            $where   = [];


            $shop_name=$map['shop_name'];//门店名称


            $uid=explode(',',$map['uid']);//进店保留客户id


            $old_enter_store_ids=$map['old_enter_store_ids'];//进店客户id


            $data=[];


            if ($old_enter_store_ids)


            {


                array_push($where, ['id', 'in', $old_enter_store_ids]);


            }else


            {


                $this->error = '暂无此数据';


                return [];


            }


            $sqlQuery = Db::name('customer')


                ->where($where);


            $dataCount  = $sqlQuery->count();


            if ($dataCount) {


                $field = ['customer_name,id'];


                $list = $sqlQuery->field($field)


                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])


                    ->order('id DESC')


                    ->select()->toArray();


                if ($list) {


                    foreach($list as &$v){


                        $v['status_desc']=in_array($v['id'],$uid)?'是':'否';


                    }


                }


            }else


            {


                $this->error = '暂无此数据';


                return [];


            }


            $data['list'] = $list?? [];


            $data['shop_name'] = $shop_name?? [];


            $data['dataCount'] = $dataCount ?? 0;


            return $data;


        } catch (\Exception $e) {


        }


    }





    /**


     * 成交保有率明细


     * @param  array $request 请求参数


     * @return array


     * @author Mr.Liu


     * @create 2021-11-27 17:25


     */


    public function getDealDetails(array $request): array


    {


        try {


            $request = $this->fmtRequest($request);


            $map     = $request['map'] ?? [];


            $where   = [];


            $shop_name=$map['shop_name'];//门店名称


            $uid=explode(',',$map['deal_uid']);//进店保留客户id


            $old_deal_ids=$map['old_deal_ids'];//进店客户id


            $data=[];


            if ($old_deal_ids)


            {


                array_push($where, ['id', 'in', $old_deal_ids]);


            }else


            {


                $this->error = '暂无此数据';


                return [];


            }


            $sqlQuery = Db::name('customer')


                ->where($where);


            $dataCount  = $sqlQuery->count();


            if ($dataCount) {


                $field = ['customer_name,id'];


                $list = $sqlQuery->field($field)


                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])


                    ->order('id DESC')


                    ->select()->toArray();


                if ($list) {


                    foreach($list as &$v){


                        $v['status_desc']=in_array($v['id'],$uid)?'是':'否';


                    }


                }


            }else


            {


                $this->error = '暂无此数据';


                return [];


            }


            $data['list'] = $list?? [];


            $data['shop_name'] = $shop_name?? [];


            $data['dataCount'] = $dataCount ?? 0;


            return $data;


        } catch (\Exception $e) {


        }


    }

    public function sumShopPayMoneyNewMZAll($scene,$shopIds,$startTime,$endTime){
        $where = [];
		switch ($scene) {
			case 'XD':

		        // $where['r.order_type']=1;
                array_push($where,['r.order_type','=',1]);
				break;

		    case 'BD':

		        // $where['r.order_type']=2;
                array_push($where,['r.order_type','=',2]);
				break;

		    default:

		        break;

		}
        if(!empty($shopIds))
        {
            array_push($where,['r.shop_id','in',$shopIds]);
        }
		//收款单 收款类型是 收款 且不含收款方式不是店转的
		$receive = Db::name('shop_refund_order')->alias('r')

//		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
		    ->field('sum(r.pay_amount) as pay_amount,r.shop_id')
		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
		    ->where($where)
		    // ->where('r.shop_id','=',$shopId)

//		    ->where('g.refund_mode','<>','06')
            ->where('id', 'IN', function ($query) {
                $query->table('xy_shop_refund_order_goods')->where('refund_mode','<>','06')->field('order_id');
            })

		    ->where('r.type','=',3)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();
            ->group('r.shop_id')->select()->toArray();
		    // ->column('r.pay_amount as pay_amount','r.id');
			//->column('r.pay_amount * r.coefficient as pay_amount','r.id');

		//var_dump($receive);
		//退款单
		$refund = Db::name('shop_refund_order')->alias('r')

		    ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

		    // ->field('sum(r.pay_amount * r.coefficient) as pay_amount')
            ->field('sum(r.pay_amount) as pay_amount,r.shop_id')

		    // ->where('r.shop_id','=',$shopId)

		    ->where('g.refund_mode','<>','06')

		    ->where('r.type','=',1)

		    ->where('r.status','=',2)

		    ->where('r.refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })

		    // ->find();

		    //->column('r.pay_amount * r.coefficient as pay_amount','r.id');
			// ->column('r.pay_amount  as pay_amount','r.id');
            ->group('r.shop_id')->select()->toArray();

		// return round($receive['pay_amount'] -$refund['pay_amount'],2);

		// $receive_sum = array_sum($receive);

		// $refund_sum = array_sum($refund);

		// return bcsub($receive_sum,$refund_sum,2);
        $data = [];
		foreach($receive as $value)
		{
			$data[$value['shop_id']]=$value['pay_amount'];
		}
		foreach($refund as $value)
		{
			if(empty($data[$value['shop_id']]))
			{
				$data[$value['shop_id']] = $value['pay_amount'];
			}else{
				$data[$value['shop_id']] -= $value['pay_amount'];
			}
		}

		return $data;
	}
    	/*
	 * @ 新单金额和补单金额的 计算 逻辑----川渝市场的 新单/补单业绩计算
	 *
	 * @ 门店新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
	 *                       【加上】  门诊转到门店的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
	 *
	 * @ 门珍新单/补单业绩计算 ：收款单（不含店转）的新单/补单 实收金额 【减去】 退款单（不含店转）的新单/补单 实收金额
	 *                       【加上】  非疗程不含店转的 新单/补单 实收金额 【减去】 退款单是店转的 新单/补单金额 【加上】 收款单是店转的新单/补单金额；
	 */
	public function sumShopPayMoneyNewAll($scene,$shopIds,$shop_type,$startTime,$endTime){
		$where = [];
        $wheret = [];
		switch ($scene) {
			case 'XD':

		        // $where['order_type']=1;
				// $wheret['r.order_type']=1;
                array_push($where,['order_type','=',1]);
                array_push($wheret,['r.order_type','=',1]);
				break;

		    case 'BD':

		        // $where['order_type']=2;
				// $wheret['r.order_type']=2;
                array_push($where,['order_type','=',2]);
                array_push($wheret,['r.order_type','=',2]);
				break;

		    default:

		        break;

		}
        if(!empty($shopIds))
        {
            array_push($wheret,['r.shop_id','in',$shopIds]);
        }
		//收款单中的疤痕业绩 不含店转的业绩--01
		$receive = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			// ->field('sum(g.pay_price) as pay_amount,r.shop_id')
	        // ->where('r.shop_id','=',$shopId)

	        ->where($wheret)

	        ->where('g.refund_mode','<>','06')

	        ->where('r.type','=',3)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })
	        ->group('r.shop_id')
	        ->column('sum(g.pay_price) as pay_amount','r.shop_id');

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//退款单中的疤痕业绩	--不含店转的业绩  --02
		$refund = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        //->field('sum(g.pay_price * r.coefficient) as pay_amount')
			// ->field('sum(g.pay_price) as pay_amount')
	        // ->where('r.shop_id','=',$shopId)

	        ->where($wheret)

	        ->where('g.refund_mode','<>','06')

	        ->where('r.type','=',1)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

	        ->group('r.shop_id')
	        ->column('sum(g.pay_price) as pay_amount','r.shop_id');

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');

	    if(!empty($shopIds))
        {
            $whered = array_merge($where,[['referral_shop_id','in',$shopIds]]);
        }else{
            $whered = $where;
        }
		//门诊转店到 门店的 通过门店的归属ID 查询	--收款单 --03
		$receive_zd =Db::name('shop_refund_order')

		    // ->field('sum(pay_amount * coefficient) as pay_amount')

			->where($whered)

            ->where('type','=',3)

		    ->where('status','=',2)

		    ->where('refund_type','=','101.02')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
            ->group('referral_shop_id')
	        ->column('sum(pay_amount * coefficient) as pay_amount','referral_shop_id');


		//退款单是店转的 疤痕/项目业绩查询  --04
		$refund_dz = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        // ->field('sum(g.pay_price * r.coefficient) as pay_amount')

	        ->where($wheret)

	        // ->where('r.shop_id','=',$shopId)

	        ->where('g.refund_mode','=','06')

	        ->where('r.type','=',1)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','<>','101.03')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })

	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

            ->group('shop_id')
	        ->column('sum(g.pay_price * r.coefficient) as pay_amount','shop_id');

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


		//收款单是店转的 疤痕/项目业绩---05
		$receive_dz = Db::name('shop_refund_order')->alias('r')

	        ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')

	        // ->field('sum(g.pay_price * r.coefficient) as pay_amount')

	        // ->where('r.shop_id','=',$shopId)

	        ->where($wheret)

	        ->where('g.refund_mode','=','06')

	        ->where('r.type','=',3)

	        ->where('r.status','=',2)

	        ->where('r.refund_type','=','101.02')

	        ->when($startTime ?? 0, function ($query) use ($startTime) {

	            return $query->whereTime('deal_time', '>=', $startTime);

	        })
	        ->when($endTime ?? 0, function ($query) use ($endTime) {

	            return $query->whereTime('deal_time', '<=', $endTime);

	        },function ($query) use ($endTime) {

	            return $query->whereMonth('deal_time');

	        })

            ->group('shop_id')
	        ->column('sum(g.pay_price * r.coefficient) as pay_amount','shop_id');

	        // ->column('r.pay_amount * r.coefficient as pay_amount','r.id');


            if(!empty($shopIds))
            {
                $whered = array_merge($where,[['shop_id','in',$shopIds]]);
            }else{
                $whered = $where;
            }
		//门诊收款单 是非疗程的 疤痕/项目业绩  --06
		$receive_mz =Db::name('shop_refund_order')

		    // ->field('sum(pay_amount * coefficient) as pay_amount')

			->where($whered)

		    // ->where('shop_id','in',$shopIds)

			->where('is_treatment','=',2)

		    ->where('type','=',3)

			->where('referral_shop_id','>',0)

		    ->where('status','=',2)

		    ->where('refund_type','<>','101.03')

		    ->when($startTime ?? 0, function ($query) use ($startTime) {

		        return $query->whereTime('deal_time', '>=', $startTime);

		    })

		    ->when($endTime ?? 0, function ($query) use ($endTime) {

		        return $query->whereTime('deal_time', '<=', $endTime);

		    },function ($query) use ($endTime) {

		        return $query->whereMonth('deal_time');

		    })
            ->group('shop_id')
	        ->column('sum(pay_amount * coefficient) as pay_amount','shop_id');

		// if($shop_type==1){ //1是门诊 2是门店
		// 	//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
		// 	// return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
		// }else{
		// 	//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
		// 	return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
		// }
		$data = [];
		foreach($receive as $key => $value)
		{
			$data[$key]['receive']=$value;
		}

		foreach($refund as $key => $value)
		{
			$data[$key]['refund']=$value;
		}

		foreach($receive_dz as $key => $value)
		{
			$data[$key]['receive_dz']=$value;
		}
		foreach($receive_mz as $key => $value)
		{
			$data[$key]['receive_mz']=$value;
		}
		foreach($refund_dz as $key => $value)
		{
			$data[$key]['refund_dz']=$value;
		}
		foreach($receive_zd as $key => $value)
		{
			$data[$key]['receive_zd']=$value;
		}
		foreach($data as $key => $value)
		{
			if(empty($value['refund']))
			{
				$data[$key]['refund']=0;
			}
			if(empty($value['receive']))
			{
				$data[$key]['receive']=0;
			}
			if(empty($value['receive_dz']))
			{
				$data[$key]['receive_dz']=0;
			}
			if(empty($value['receive_mz']))
			{
				$data[$key]['receive_mz']=0;
			}
			if(empty($value['refund_dz']))
			{
				$data[$key]['refund_dz']=0;
			}
			if(empty($value['receive_zd']))
			{
				$data[$key]['receive_zd']=0;
			}
		}
        $result = [];
		if($shop_type==1){ //1是门诊 2是门店
			//return round($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']+bcsub(0,$receive_mz['pay_amount'],2)+bcsub(0,$refund_dz['pay_amount']),2);
			// return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_dz['pay_amount']-$receive_mz['pay_amount']-$refund_dz['pay_amount']),2);
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_dz']-$value['receive_mz']-$value['refund_dz']),2);
			}
		}else{
			//实收金额 - 退款金额 + 门诊收钱分给店面的一半金额
			// return round(($receive['pay_amount']-$refund['pay_amount'] +$receive_zd['pay_amount']+$receive_dz['pay_amount']-$refund_dz['pay_amount']),2);
			foreach($data as $key =>$value)
			{
				$result[$key] = round(($value['receive']-$value['refund'] +$value['receive_zd']+$value['receive_dz']-$value['refund_dz']),2);
			}
		}
		return $result;
	}





























}


